from fastapi import APIRouter, Request, Form, Depends, HTTPException, status
from fastapi.responses import RedirectResponse
import hashlib
from fastapi.templating import Jinja2Templates
import os
router = APIRouter()

templates = Jinja2Templates(directory="templates")
# 从环境变量中获取用户名和密码
USERNAME = os.getenv("USERNAME")
PASSWORD = os.getenv("PASSWORD")

@router.get("/login")
async def get_login_page(request: Request, error: bool = False):
    # 返回login.html页面，并传递error参数
    return templates.TemplateResponse("login.html", {"request": request, "error": error})

@router.post("/login")
async def login(request: Request,username: str = Form(...), password: str = Form(...)):
    stored_password_hash = md5_hash(PASSWORD)
    if username == USERNAME and password == stored_password_hash:
        # 登录成功，重定向到首页
        request.session['user'] = username  # 在会话中设置用户
        response = RedirectResponse(url='/', status_code=303)
        return response
    else:
        response = RedirectResponse(url='/login?error=true', status_code=303)
        return response

@router.get("/logout")
def logout(request: Request):
    # 清除会话中的用户信息
    request.session.pop('user', None)
    # 重定向到登录页面
    return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)

# 创建MD5哈希函数
def md5_hash(string):
    return hashlib.md5(string.encode()).hexdigest()


# 获取当前登录用户
def get_current_user(request: Request):
    user = request.session.get('user')
    if not user:
        # 用户未登录，抛出异常并重定向到登录页
        raise HTTPException(
            status_code=status.HTTP_303_SEE_OTHER,
            detail="未授权访问: 用户未登录",
            headers={"Location": "/login"}
        )
    return user
